package top.hcode.hoj.schedule;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.nutz.lang.Times;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import top.hcode.hoj.common.LazyDao;
import top.hcode.hoj.manager.coll.ItechCollQuestionJudgeManger;
import top.hcode.hoj.service.LockService;

import java.util.Date;

/**
 * 客观题评分
 *
 * @author orangej
 * @since 2025/2/17
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ResetCollUserAnswerJudgeStateJob {

    private final LockService lockService;
    private final LazyDao dao;

    private static final String LOCK_KEY = "key:ResetCollUserAnswerJudgeStateJob";

    @Scheduled(fixedRate = 1000 * 60 * 3)
    public void execute() {
        boolean locked = false;
        try {
            locked = lockService.tryLock(LOCK_KEY, 120);
            if (!locked) {
                return;
            }

            // 超过5分钟，恢复为未判题状态
            dao.runSql("update coll_user_answer set judge_state = 0, judging_teacher_id = null ,judge_lock_at = null " +
                    "where judge_state = 1 and judge_lock_at < ?", Times.nextMinute(new Date(), 5));
        } finally {
            if (locked) {
                lockService.releaseLock(LOCK_KEY);
            }
        }


    }
}
